package com.lj.framework.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.lj.common.utils.security.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;

/**
 * 配置MybatisPlus自动填充功能实现
 *
 * @author 小李飞刀
 */
@Component
@Slf4j
public class MpMetaObjectHandler implements MetaObjectHandler {

    /**
     * 插入时候自动填充
     *
     * @param metaObject 对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            fillStrategy(metaObject, "createTime", new Timestamp(System.currentTimeMillis()));
            fillStrategy(metaObject, "updateTime", new Timestamp(System.currentTimeMillis()));
            fillStrategy(metaObject, "delFlag", "0");
            fillStrategy(metaObject, "createBy", SecurityUtil.getUserId().toString());
            fillStrategy(metaObject, "updateBy", SecurityUtil.getUserId().toString());
        } catch (Exception e) {
            // do nothing
        }
    }

    /**
     * 更新时候自动填充
     *
     * @param metaObject 对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            fillStrategy(metaObject, "updateTime", new Timestamp(System.currentTimeMillis()));
            fillStrategy(metaObject, "updateBy", SecurityUtil.getUserId());
        } catch (Exception e) {
            // do nothing
        }
    }

}